//
//  SampleNetWorks.swift
//  SampleNetWorks
//
//  Created by apple on 15/3/4.
//  Copyright (c) 2015年 Ai. All rights reserved.
//

import Foundation

enum HTTPMethod:String{
    case POST = "POST"
    case GET = "GET"
}

public class SampleNeworks{
    
    
    
    typealias Completion = (result:AnyObject?,error:NSError?)->()
    
  
    ///  异步加载数据
    ///
    ///  :param: urlString  图片网址
    ///  :param: completion 回调
    func requestImage(urlString:String,completion:Completion)->(){
        downloadImage(urlString, completion: { (result, error) -> () in
            if error != nil{
                completion(result: nil, error: error)
            }else{
                var path = self.fullPath(urlString)
                var image = UIImage(contentsOfFile: path)
                
                // 在主线程回调
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    completion(result: image, error: nil)
                })
            }
        })
    }
    
    ///  缓存路径
    ///
    ///  :param: urlString 图片地址
    ///
    ///  :returns: 对应图片在缓存中得路径
    func fullPath(urlString:String)->String{
        var path = urlString.md5
        return self.cacheImageUrl!.stringByAppendingPathComponent(path)
        
    }
    
    ///  下载多张图片
    ///
    ///  :param: urlStrings 图片数组
    ///  :param: completion 回调
    func downloadImages(urls:[String],completion:Completion)->(){
        
        // 创建调度组,统一监听异步调度任务
        let group = dispatch_group_create()
        for url in urls {
            // 入组
            dispatch_group_enter(group)
            downloadImage(url, completion: { (result, error) -> () in
                // 出组
                dispatch_group_leave(group)
            })
        }
        //为group设置通知一个block，当group关联的block执行完毕后，就调用这个block
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            completion(result: nil, error: nil)
        }
    }
    
    
    ///  缓存单张图片
    ///
    ///  :param: urlString  图片路径
    ///  :param: completion 回调
    func downloadImage(urlString:String,completion:Completion)->(){
        // 1.下载路径md5,
//        var path = urlString.md5
////        println("md5----\(path)")
//        path = cacheImageUrl!.stringByAppendingPathComponent(path)
        var path = fullPath(urlString)
//        println("\(path)")
        // 2.缓存检测
        if NSFileManager.defaultManager().fileExistsAtPath(path){
//            println("\(urlString)已经被缓存")
            completion(result: nil, error: nil)
            return
        }
        // 3.下载图像
       if let url = NSURL(string: urlString){
   
                self.session!.downloadTaskWithURL(url, completionHandler: { (location, _, error) -> Void in
                    // 3.1处理错误
                    if error != nil{
                        completion(result: nil, error: error)
                        return
                    }
                    // 3.2 复制文件
                    NSFileManager.defaultManager().copyItemAtPath(location.path!, toPath: path, error: nil)
                    // 3.3 回调,不传递任何参数
                    completion(result: nil, error: nil)
                }).resume()
       }else{
        let error = NSError(domain: "NB----Error", code: -1, userInfo: ["error":"无法创建URL"])
        completion(result: nil, error: error)
        }
    }
    
    
    
    
   private static var cachePath = "MyImgCacheFolder"
 /// 缓存图片路径懒加载
   private lazy var cacheImageUrl :String? = {
        // 1.创建缓存路径
    var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as! String
        path = path.stringByAppendingPathComponent(cachePath)
        
        // 2.检查该目录是否存在
        var isDirectory : ObjCBool = true
        var exists = NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory)
//        println("isdirectory-\(isDirectory)   exists-\(exists) path -\(path)")
        
        // 3.如果存在的是文件，不是目录，删除
        if  !isDirectory && exists{
            
            NSFileManager.defaultManager().removeItemAtPath(path, error: nil)
        }
        
        // 4.如果该目录不存在，创建
        NSFileManager.defaultManager().createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil, error: nil)
        return path
    }()
    
    
    
    
    ///  session懒加载
   private lazy var session : NSURLSession? = {
        
        return NSURLSession.sharedSession()
        }()
    
    public typealias completions = (result:AnyObject?,error:NSError?) ->()
    
    ///  请求Json
    ///
    ///  :param: method     请求方法
    ///  :param: urlString  urlString
    ///  :param: params     可选字典参数
    ///  :param: completion 回调---闭包
     func requestJson(method:HTTPMethod,urlString:String,params:[String:String]?,completion:completions){
        
        if let req = request(method, urlString: urlString, params: params){
    
            session!.dataTaskWithRequest(req, completionHandler: { (data, _, error) -> Void in
                // 如果有错误
                if error != nil {
                    completion(result: nil, error: error)
                    return
                }else{
                    // 如果没有错误
                    let json: AnyObject?  = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil)
                    
                    // 反序列化失败
                    if json == nil{
                        let error = NSError(domain: "NB----Error", code: 0, userInfo: ["error" : "序列化失败"])
                        completion(result: nil, error: error)
                    }else{
                        // 序列化成功
                        dispatch_async(dispatch_get_main_queue(), { () -> Void in
                            completion(result: json, error: nil)
                        })
                    }
                }
            }).resume()
        } else {
            let error = NSError(domain: "NB----Error", code: -1, userInfo: ["error" : "请求失败"])
            
            completion(result: nil, error: error)
        }
    }
    
    ///  网络请求
    ///
    ///  :param: method    请求方法
    ///  :param: urlString 网址
    ///  :param: params    可选字典
   private func request(method:HTTPMethod,urlString:String,params:[String:String]?) -> NSURLRequest?{
        
        var req : NSMutableURLRequest?
        
        //urlString.isEmpty
        if urlString.isEmpty{
            return nil
        }
        // 取出拼接好的参数
        var str = urlString
        if method == HTTPMethod.GET{
            let query = queryString(params)
            // GET 请求
            if query != nil {
                str += "?" + query!
            }
            req = NSMutableURLRequest(URL: NSURL(string: str)!)
            
        }else{
            // POST请求
            if let query = queryString(params) {

                req = NSMutableURLRequest(URL: NSURL(string: str)!)
                req!.HTTPMethod = method.rawValue
                req!.HTTPBody = query.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
            }
        }
        return req
    }
    
    
    ///  拼接字符串
    ///
    ///  :param: params 可选字典
    private func queryString(params:[String:String]?)->String?{
        if params == nil{
            return nil
        }
        var array = [String]()
        for(k,var v) in params!{
           // v = v.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
            let str = k + "=" + v
            array .append(str)
        }
        // 最后返回 "name = zhangsan & age = 34"
        return join("&", array)
        
    }
    
    // 构造初始化函数
//    public init(){
//        
//    }
    
    
}